package com.zztl.infiniteBand.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.net.Uri
import android.provider.MediaStore
import android.provider.Settings
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.Base64
import android.view.LayoutInflater
import android.view.View
import com.zztl.infiniteBand.BraceletApplication
import java.io.*
import java.util.regex.Pattern

/**
 * Created by lsm on 2016/9/6.
 */

object UiUtils {
    val EMPTY = 1
    val ERRO = 2
    val SUCCESS = 3

    /**
     * @return 全局Context
     */
    val context: Context
        get() = BraceletApplication.context


    private//        LshLogUtils.i("MiuiVersion = " + line);
    val miuiVersion: String?
        get() {
            val propName = "ro.miui.ui.version.name"
            val line: String
            var input: BufferedReader? = null
            try {
                val p = Runtime.getRuntime().exec("getprop $propName")
                input = BufferedReader(
                        InputStreamReader(p.inputStream), 1024)
                line = input.readLine()
                input.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
                return null
            } finally {
                try {
                    input!!.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
            return line
        }

    fun getString(resId: Int): String {
        return context.resources.getString(resId)
    }

    fun getDimens(resId: Int): Int {
        return context.resources.getDimensionPixelSize(resId)
    }

    fun getColor(resId: Int): Int {
        return context.resources.getColor(resId)
    }

    fun getDrawable(resId: Int): Drawable {
        return context.resources.getDrawable(resId)
    }


    fun getBitmapFormUri(ac: Activity, uri: Uri): Bitmap? {
        var input: InputStream? = null
        try {
            input = ac.contentResolver.openInputStream(uri)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        val onlyBoundsOptions = BitmapFactory.Options()
        onlyBoundsOptions.inJustDecodeBounds = true
        onlyBoundsOptions.inDither = true//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions)
        try {
            input!!.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        val originalWidth = onlyBoundsOptions.outWidth
        val originalHeight = onlyBoundsOptions.outHeight
        if (originalWidth == -1 || originalHeight == -1) {
            return null
        }

        onlyBoundsOptions.inJustDecodeBounds = false // 获取新的大小
        val sampleSize = (onlyBoundsOptions.outHeight / 200.toFloat()).toInt()
        /* if (sampleSize <= 0) {
          sampleSize = 1;
      }*/
        //比例压缩
        val bitmapOptions = BitmapFactory.Options()
        bitmapOptions.inSampleSize = sampleSize//设置缩放比例
        bitmapOptions.inDither = true//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888//optional
        try {
            input = ac.contentResolver.openInputStream(uri)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        val bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions)
        try {
            input!!.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return bitmap
    }


    fun compressImage(image: Bitmap): Bitmap {

        val baos = ByteArrayOutputStream()
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos)//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 100
        while (baos.toByteArray().size / 1024 > 200) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset()//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos)//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10//每次都减少10
        }
        val isBm = ByteArrayInputStream(baos.toByteArray())//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null)
    }


    fun bitmap2Base64(bitmap: Bitmap?): String {
        if (bitmap == null) {
            return ""
        }
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val bytes = baos.toByteArray()
        //base64 encode
        val encode = Base64.encode(bytes, Base64.DEFAULT)
        return String(encode)
    }

    /*
    public static Bitmap getSmallBitmap(Context context, String path) {
//        BitmapFactory.Options opt = new BitmapFactory.Options();
//        opt.inPreferredConfig = Bitmap.Config.RGB_565;
//        opt.inPurgeable = true;
//        opt.inInputShareable = true;
//        return BitmapFactory.decodeFile(path, opt);
        File newFile = new CompressHelper.Builder(context)
//                .setBitmapConfig(Bitmap.Config.ARGB_8888)
                .setMaxWidth(1200)  // 默认最大宽度为720
                .setMaxHeight(1500) // 默认最大高度为960*//*
                .setQuality(80)    // 默认压缩质量为80
                .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
                .build()
                .compressToFile(new File(path));

        return BitmapFactory.decodeFile(newFile.getAbsolutePath());
    }
    */


    /**
     * @Desc: dip转化为px
     */
    fun dip2px(context: Context, dip: Int): Int {
        val scale = context.resources.displayMetrics.density
        return (dip * scale + 0.5f).toInt()
    }

    /**
     * @Desc: px转化为dip
     */
    fun px2dip(context: Context, px: Int): Int {
        val scale = context.resources.displayMetrics.density
        return (px / scale + 0.5f).toInt()
    }

    /**
     * sp转化为px
     *
     * @param context
     * @param sp
     * @return
     */
    fun sp2px(context: Context, sp: Int): Int {
        val scale = context.resources.displayMetrics.scaledDensity
        return (sp * scale + 0.5f).toInt()
    }

    fun inflate(resId: Int): View {
        return LayoutInflater.from(context).inflate(resId, null, false)
    }

    // This snippet hides the system bars.
    fun hideSystemUI(activity: Activity) {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        activity.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                //                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar

                or View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar

                or View.SYSTEM_UI_FLAG_IMMERSIVE or View.INVISIBLE)
    }

    fun hideStickySystemUI(activity: Activity) {
        activity.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }

    fun showSystemUI(activity: Activity) {
        activity.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    }


    //    decorView.setSystemUiVisibility(
    //    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    //                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    //                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    //                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    //                | View.SYSTEM_UI_FLAG_FULLSCREEN
    //                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}


    fun matcherSearchText(color: Int, text: String, keyword: String): SpannableString {
        val ss = SpannableString(text)
        val pattern = Pattern.compile(keyword)
        val matcher = pattern.matcher(ss)

        while (matcher.find()) {
            val start = matcher.start()
            val end = matcher.end()
            ss.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        return ss
    }

    /**
     * 获取跳转「应用详情」的意图
     *
     * @param packageName 应用包名
     * @return 意图
     */
    fun getAppDetailsSettingsIntent(packageName: String): Intent {
        return Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                .setData(Uri.parse("package:$packageName"))
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }

    /**
     * 跳转:「应用详情」界面
     *
     * @param packageName 应用包名
     */
    fun gotoAppDetailSetting(packageName: String) {
        context!!.startActivity(getAppDetailsSettingsIntent(packageName))
    }

    fun uriToFile(uri: Uri): File? {
        var path: String? = null
        if ("file" == uri.scheme) {
            path = uri.encodedPath
            if (path != null) {
                path = Uri.decode(path)
                val cr = context.contentResolver
                val buff = StringBuffer()
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'$path'").append(")")
                val cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA), buff.toString(), null, null)
                var index = 0
                var dataIdx :Int
                cur!!.moveToFirst()
                while (!cur.isAfterLast) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID)
                    index = cur.getInt(index)
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    path = cur.getString(dataIdx)
                    cur.moveToNext()
                }
                cur.close()
                if (index == 0) {
                } else {
                    val u = Uri.parse("content://media/external/images/media/$index")
                    println("temp uri is :$u")
                }
            }
            if (path != null) {
                return File(path)
            }
        } else if ("content" == uri.scheme) {
            // 4.2.2以后
            val proj = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = context.contentResolver.query(uri, proj, null, null, null)
            if (cursor!!.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                path = cursor.getString(columnIndex)
            }
            cursor.close()

            return File(path!!)
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null
    }

}
 fun String.toast(context: Context?=UiUtils.context){
     context?.let {
         ToastUtils.show(it,this)
     }
}

infix fun Context.toast(msg:String){
    ToastUtils.show(this,msg)
}



/*inline fun BaseActivity.skipActivity(activity: Activity,vararg params: kotlin.Pair<kotlin.String, kotlin.Any>){
    Intent(this,activity::class.java).apply {
            for(entity in params){
                putExtra(entity.first,entity.second)
            }
    }
}*/
